/**
 * 
 */
package weibo4j.examples;

import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;

import weibo4j.Timeline;
import weibo4j.Users;
import weibo4j.examples.oauth2.Log;
import weibo4j.http.HttpClient;
import weibo4j.http.ImageItem;
import weibo4j.model.PostParameter;
import weibo4j.model.Status;
import weibo4j.model.StatusWapper;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONArray;
import weibo4j.org.json.JSONObject;
import weibo4j.util.WeiboConfig;

/**
 * 微博主要接口
 * @author Administrator
 * 
 */
public class WeiboMessage {
	public static byte[] readInputStream(InputStream is) { 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
        byte[] buffer = new byte[1024]; 
        int length = -1; 
        try { 
            while ((length = is.read(buffer)) != -1) { 
                baos.write(buffer, 0, length); 
            } 
            baos.flush(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        byte[] data = baos.toByteArray(); 
        try { 
            is.close(); 
            baos.close(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return data; 
    } 
	public static byte[] readFileImage(String filename) throws IOException {
		Image image = null;
		byte[] data = null; 
		URL url = new URL(filename); 
		//BufferedInputStream bis = new BufferedInputStream(url.openStream());
		//image = ImageIO.read(bufferedInputStream);
		HttpURLConnection connect = (HttpURLConnection) url.openConnection();
		connect.setDoInput(true);
		connect.setRequestMethod("GET"); 
		connect.setConnectTimeout(6000); 
		connect.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");//伪装成浏览器访问
		InputStream is  = connect.getInputStream(); 
		if (connect.getResponseCode() == 200) { 
            data = readInputStream(is); 
        } else{ 
            data=null; 
        } 
		try { 
            if(is != null){ 
                is.close(); 
            }                
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
		connect.disconnect();
		/*
		BufferedInputStream bis=new BufferedInputStream(connect.getInputStream());
		connect.connect();
		
		int filesize = connect.getContentLength();
		byte[] bytes = new byte[filesize];

		int len = bis.available();
		int r = bis.read(bytes);
		if (len != r) {
			bytes = null;
			throw new IOException("读取文件不正确");
		}
		bis.close();*/
		return data;
	}
	//发送微博带图片
	public static StatusWapper sendOfPicUrl(String access_token,String message,String url){
		HttpClient client = new HttpClient();
		client.setToken(access_token);
		StatusWapper status = null;

		try {

			status=Status.constructWapperStatus(client.get(
					WeiboConfig.getValue("baseURL")	+ "statuses/upload_url_text.json",
					new PostParameter[] {
							new PostParameter("status", message),
							new PostParameter("url ", url)}));
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return status;
	}
	//发布一条微博信息，要前后内容不一致
	public static Status sendOfPic(String access_token,String message,String pic){
		byte[] content;
		Status status = null;
		try {
			content = readFileImage(pic);
			ImageItem pics = new ImageItem("pic", content,pic);
			String s = java.net.URLEncoder.encode(message, "utf-8");
			Timeline tm = new Timeline();
			tm.client.setToken(access_token);
			status = tm.UploadStatus(s,pics);
			Log.logInfo(status.toString());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}catch (WeiboException e) {
			e.printStackTrace();
		}

		
		return status;
	}
	//发布一条微博信息，要前后内容不一致
	public static Status send(String access_token,String message){
		Timeline tm = new Timeline();
		tm.client.setToken(access_token);
		Status status = null;
		try {
			status = tm.UpdateStatus(message);
			Log.logInfo(status.toString());
		} catch (WeiboException e) {
			e.printStackTrace();
		}	
		return status;
	}
	//注意，获取有次数限制的
	public static StatusWapper getLastedByUser(String access_token,String name,int count){
		HttpClient client = new HttpClient();
		client.setToken(access_token);
		StatusWapper status = null;
		try {
			status=Status.constructWapperStatus(client.get(
					WeiboConfig.getValue("baseURL")	+ "statuses/user_timeline.json",
					new PostParameter[] {
							new PostParameter("screen_name", name),
							new PostParameter("count", count)}));
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return status;
	}
	//获取最新的公共微博,单页返回的记录条数，最大不超过200，默认为20
	//返回结果非完全实时,可能带缓存，几次结果都一样
	public static StatusWapper getLastedPublic(String access_token,int count){
		Timeline tm = new Timeline();
		tm.client.setToken(access_token);
		StatusWapper status = null;
		try {
			status = tm.getPublicTimeline(count,0);
			for(Status s : status.getStatuses()){
				Log.logInfo(s.toString());
			}
			//System.out.println(status.getNextCursor());
			//System.out.println(status.getPreviousCursor());
			//System.out.println(status.getTotalNumber());
			//System.out.println(status.getHasvisible());
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		return status;
	}
	//id,转发的微博ID,message,不填则默认为“转发微博”，is_comment，0：否、1：评论给当前微博、2：评论给原微博、3：都评论，默认为0 。 
	public static Status resend(String access_token,String id,String message,int is_comment){
		Timeline tm = new Timeline();
		tm.client.setToken(access_token);
		Status status = null;
		try {
			status = tm.Repost(id,message,is_comment);
			Log.logInfo(status.toString());
		} catch (WeiboException e) {
			e.printStackTrace();
		}	
		return status;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String access_token = WeiboContants.access_token;
		String uid =WeiboContants.uid;
		String domain =WeiboContants.domain;
		send(access_token,"测试下微博自动挂机发布内容！要前后内容不一致");
		/*
		StatusWapper status=getLastedPublic(access_token,10);
		List l=status.getStatuses();
		for(int i=0;i<l.size();i++){
			Status s=(Status) l.get(i);
			resend(access_token,s.getId(),"蛇年春节,健康重要,平安第一,请关注我,转发我,评论我,@CTO沙龙俱乐部,@"+s.getUser().getName()+",即可参与春节后抽奖！ipad mini,iphone5,三星等手机!！"+i,3);
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			
		}*/
	}

}
